﻿using System;
using System.Collections.Generic;
using System.Linq;
using Framework.DataAccess;
using Project.Domain.Entities;

namespace Project.DAL.Repository
{
    public interface IUserRepository :IRepository<User>
    {
        IEnumerable<User> GetAllUser();
        User GetUserById(int id);
        User GetUserByName(string username);
        bool CreateUser(User user);        
        bool CountAdmin();                
        bool Checkactive(string username);
        bool IsAdmin(string userName);        
    }

    public class UserRepository : RepositoryBase<User>, IUserRepository
    {
        public UserRepository(IDatabaseFactory databaseFactory)
            : base(databaseFactory)
        {

        }

        #region "GetAllUser"
        public IEnumerable<User> GetAllUser()
        {
            return GetAll().Where(u => u.IsAdmin != true);
        }

        #endregion

        #region "GetUserById"
        public User GetUserById(int id)
        {
            return Get(u => u.UserId == id);            
        }
        #endregion

        #region "GetUserByName"
        public User GetUserByName(string username)
        {
            return Get(u => u.UserName == username);
        }
        #endregion

        #region "CreateUser"
        public bool CreateUser(User user)
        {
            try
            {
                Add(user);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion


        #region "SaveChange"        

        //return True if Fount User Have properties Admin=true
        public bool CountAdmin()
        {
            var admin = Get(u => u.IsAdmin);            
            return admin != null;
        }

        public bool Checkactive(string username)
        {
            var user = Get(u => u.UserName.Equals(username));            
            return user.Active;
        }

        #endregion                              

        public bool IsAdmin(string userName)
        {
            var user = Get(u => u.UserName.Equals(userName));
            return user != null && user.IsAdmin;
        }
    }
}